#!/usr/bin/env python3
"""
Script to analyze the maximum nesting depth of itemize environments.
The issue might be progressive increase in nesting depth across chapters.
"""
import os
import re
import glob

def analyze_nesting_depth(filepath):
    """Analyze the maximum nesting depth of itemize environments in a file."""
    try:
        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
    except Exception as e:
        return {'error': str(e)}
    
    lines = content.split('\n')
    current_depth = 0
    max_depth = 0
    depth_lines = []  # Track lines with significant depth
    
    for i, line in enumerate(lines, 1):
        # Count itemize begins and ends on this line
        begins = len(re.findall(r'\\begin\{itemize\}', line))
        ends = len(re.findall(r'\\end\{itemize\}', line))
        
        current_depth += begins - ends
        max_depth = max(max_depth, current_depth)
        
        # Record lines with significant depth (>= 3)
        if current_depth >= 3:
            depth_lines.append((i, current_depth, line.strip()))
    
    # Also look for any signs of accumulated indentation issues
    problematic_patterns = []
    for i, line in enumerate(lines, 1):
        # Look for extremely long leading whitespace
        leading_space = len(line) - len(line.lstrip())
        if leading_space > 20:  # Suspiciously long indentation
            problematic_patterns.append((i, leading_space, line[:50].strip()))
    
    return {
        'file': filepath,
        'max_depth': max_depth,
        'deep_lines': depth_lines[:10],  # First 10 deep nesting lines
        'problematic_indents': problematic_patterns[:5],  # First 5 problematic lines
        'final_depth': current_depth  # Should be 0 if balanced
    }

def main():
    # Check all .tex files
    tex_files = glob.glob('part*/*.tex', recursive=True)
    tex_files.sort()
    
    print("=" * 80)
    print("LaTeX Itemize Nesting Depth Analysis")
    print("=" * 80)
    
    chapter_depths = []
    
    for tex_file in tex_files:
        if os.path.exists(tex_file):
            result = analyze_nesting_depth(tex_file)
            
            if 'error' in result:
                print(f"❌ Error reading {tex_file}: {result['error']}")
                continue
            
            chapter_num = extract_chapter_number(tex_file)
            max_depth = result['max_depth']
            chapter_depths.append((chapter_num, max_depth, tex_file))
            
            if max_depth > 3:
                print(f"⚠️  HIGH NESTING: {tex_file}")
                print(f"   Max depth: {max_depth}")
                if result['deep_lines']:
                    print(f"   Sample deep lines:")
                    for line_num, depth, content in result['deep_lines'][:3]:
                        print(f"      Line {line_num} (depth {depth}): {content}")
                
                if result['problematic_indents']:
                    print(f"   Problematic indentation:")
                    for line_num, indent, content in result['problematic_indents'][:2]:
                        print(f"      Line {line_num} ({indent} spaces): {content}")
            else:
                print(f"✓ {tex_file} - Max depth: {max_depth}")
    
    # Sort chapters by number to see progression
    chapter_depths.sort(key=lambda x: x[0])
    
    print("\n" + "=" * 80)
    print("NESTING DEPTH PROGRESSION ANALYSIS:")
    print("=" * 80)
    
    print("Chapter | Max Depth | File")
    print("-" * 50)
    
    depth_progression = []
    for ch_num, depth, filename in chapter_depths:
        if ch_num is not None:
            print(f"Ch {ch_num:2d}   |    {depth}      | {filename}")
            depth_progression.append(depth)
    
    # Check for increasing trend
    if len(depth_progression) > 10:
        early_avg = sum(depth_progression[:10]) / 10
        late_avg = sum(depth_progression[-10:]) / 10
        
        print(f"\nEarly chapters average depth: {early_avg:.1f}")
        print(f"Late chapters average depth: {late_avg:.1f}")
        
        if late_avg > early_avg + 0.5:
            print(f"🔥 TREND DETECTED: Later chapters use deeper nesting!")
            print(f"   Difference: {late_avg - early_avg:.1f} levels")
            print("   This could explain progressive indentation issues.")
    
    # Check if any files have extreme nesting
    max_overall = max(depth for _, depth, _ in chapter_depths) if chapter_depths else 0
    print(f"\nMaximum nesting depth found: {max_overall}")
    
    if max_overall >= 6:
        print("⚠️  WARNING: Very deep nesting (6+ levels) detected!")
        print("   This could cause LaTeX rendering issues.")
    elif max_overall >= 4:
        print("⚠️  CAUTION: Deep nesting (4+ levels) detected.")
    
    print("=" * 80)

def extract_chapter_number(filename):
    """Extract chapter number from filename."""
    match = re.search(r'ch(\d+)_', filename)
    return int(match.group(1)) if match else None

if __name__ == "__main__":
    main()